<template>
  <div class="app-container">
    <el-card>
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="110px">
        <el-row>
          <el-col :lg="12" :xl="8">
            <el-form-item label="模板名称：" prop="name">
              <el-input v-model="formData.name" placeholder="请输入模板名称50字以内" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="计费方式：" prop="chargeMode" required>
          <el-radio-group v-model="formData.chargeMode">
            <el-radio v-for="(item, index) in BILLING_METHODS" :key="index" :label="item.value">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <div id="fare-box" style="position: relative">
          <el-form-item v-if="formData.chargeMode !== 3" label="默认运费：" required></el-form-item>

          <!-- 按件数 -->
          <div
            id="fare-item"
            class="flex flex-wrap"
            style="position: absolute; left: 110px; top: 0"
            v-if="formData.chargeMode === 1"
          >
            <el-form-item class="custom-elform" prop="defaultCharge.firstValue">
              <el-input-number v-model="formData.defaultCharge.firstValue" :min="0" :step="1" />
              <span class="ml-5">件</span>
              <span class="ml-20 mr-20">内</span>
            </el-form-item>

            <el-form-item prop="defaultCharge.firstCashPrice" label-width="0">
              <el-input-number
                v-model="formData.defaultCharge.firstCashPrice"
                :precision="2"
                :step="0.1"
                :min="0"
              />
              <span class="ml-5">元</span>
              <span class="ml-20 mr-10">每增加：</span>
            </el-form-item>

            <el-form-item prop="defaultCharge.incrementValue" label-width="0">
              <el-input-number v-model="formData.defaultCharge.incrementValue" :min="0" :step="1" />
              <span class="ml-5">件</span>
              <span class="ml-20 mr-10">增加运费：</span>
            </el-form-item>

            <el-form-item prop="defaultCharge.incrementCashPrice" label-width="0">
              <el-input-number
                v-model="formData.defaultCharge.incrementCashPrice"
                :precision="2"
                :step="0.1"
                :min="0"
              />
              <span class="ml-5">元</span>
            </el-form-item>
          </div>

          <!-- 按重量 -->
          <div
            id="fare-item"
            class="flex flex-wrap"
            style="position: absolute; left: 110px; top: 0"
            v-if="formData.chargeMode === 2"
          >
            <el-form-item class="custom-elform" prop="defaultCharge.firstValue">
              <el-input-number v-model="formData.defaultCharge.firstValue" :min="0" />
              <span class="ml-5">kg</span>
              <span class="ml-20 mr-20">内</span>
            </el-form-item>

            <el-form-item prop="defaultCharge.firstCashPrice" label-width="0">
              <el-input-number v-model="formData.defaultCharge.firstCashPrice" :min="0" />
              <span class="ml-5">元</span>
              <span class="ml-20 mr-10">每增加：</span>
            </el-form-item>

            <el-form-item prop="defaultCharge.incrementValue" label-width="0">
              <el-input-number v-model="formData.defaultCharge.incrementValue" :min="0" />
              <span class="ml-5">kg</span>
              <span class="ml-20 mr-10">增加运费：</span>
            </el-form-item>

            <el-form-item prop="defaultCharge.incrementCashPrice" label-width="0">
              <el-input-number v-model="formData.defaultCharge.incrementCashPrice" :min="0" />
              <span class="ml-5">元</span>
            </el-form-item>
          </div>
        </div>

        <!-- 配送区域 -->
        <el-form-item v-if="formData.chargeMode !== 3" label="配送区域：">
          <el-row class="pt-5 pb-5" style="background-color: #f7f8fa">
            <el-col :span="14" class="pl-20">可配送区域</el-col>
            <el-col :span="10">
              <el-row>
                <el-col v-if="formData.chargeMode === 1" :span="6" align="center"
                  >首件（个）</el-col
                >
                <el-col v-else :span="6" align="center">首重（kg）</el-col>
                <el-col :span="6" align="center">运费（元）</el-col>
                <el-col :span="6" align="center">{{
                  this.formData.chargeMode === 2 ? '续重（kg）' : '续件（个）'
                }}</el-col>
                <el-col :span="6" align="center">续费（元）</el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form-item>

        <div v-if="formData.chargeMode !== 3" style="margin-left: 110px">
          <el-row
            v-for="(item, index) in formData.listCharge"
            :key="item.id"
            class="pt-20 pb-20"
            style="border-bottom: 1px solid #f7f8fa"
          >
            <el-col :span="14">
              <div class="flex">
                <el-col :span="22" class="pl-20">
                  <el-row class="ft-14 mb-10" v-for="ele in item.areaList" :key="ele.id">
                    <el-col>{{ ele.areaName }}</el-col>
                    <el-col class="mt-10">
                      <div v-for="city in ele.lowerList" :key="city.id" class="flex-row">
                        <div class="mt-10" style="margin-right: 5px">{{ city.areaName }}</div>
                        <div style="word-break: break-all; word-wrap: break-word">
                          <span
                            style="width: auto; display: inline-block; margin-right: 5px"
                            v-for="area in city.lowerList"
                            :key="area.id"
                            >{{ area.areaName }}</span
                          >
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </el-col>

                <el-col :span="2">
                  <el-button type="text" @click="editRegion(item)">修改</el-button>
                  <PopConfirm title="确定删除该配送区域吗？" :confirm="() => deleteRegion(index)">
                    <el-button type="text">删除</el-button>
                  </PopConfirm>
                </el-col>
              </div>
            </el-col>

            <el-col :span="10">
              <el-row>
                <el-col :span="6" align="center">
                  <el-form-item
                    :prop="'listCharge.' + index + '.firstValue'"
                    label-width="0"
                    :rules="[
                      {
                        required: true,
                        message: '请输入数量',
                        trigger: ['blur', 'change']
                      },
                      {
                        pattern: REGEX_POSITIVE_INTEGER,
                        message: '请输入正整数',
                        trigger: ['blur', 'change']
                      }
                    ]"
                  >
                    <el-input v-model="item.firstValue" style="height: 30px; padding: 0 10px" />
                  </el-form-item>
                </el-col>
                <el-col :span="6" align="center">
                  <el-form-item
                    :prop="'listCharge.' + index + '.firstCashPrice'"
                    label-width="0"
                    :rules="[
                      {
                        required: true,
                        message: '请输入金额',
                        trigger: ['blur', 'change']
                      },
                      {
                        pattern: REGEX_PRICE_NUMBER,
                        message: '请输入整数，可保留两位小数',
                        trigger: ['blur', 'change']
                      }
                    ]"
                  >
                    <el-input v-model="item.firstCashPrice" style="height: 30px; padding: 0 10px" />
                  </el-form-item>
                </el-col>
                <el-col :span="6" align="center">
                  <el-form-item
                    :prop="'listCharge.' + index + '.incrementValue'"
                    label-width="0"
                    :rules="[
                      {
                        required: true,
                        message: '请输入数量',
                        trigger: ['blur', 'change']
                      },
                      {
                        pattern: REGEX_POSITIVE_INTEGER,
                        message: '请输入正整数',
                        trigger: ['blur', 'change']
                      }
                    ]"
                  >
                    <el-input v-model="item.incrementValue" style="height: 30px; padding: 0 10px" />
                  </el-form-item>
                </el-col>
                <el-col :span="6" align="center">
                  <el-form-item
                    :prop="'listCharge.' + index + '.incrementCashPrice'"
                    :rules="[
                      {
                        required: true,
                        message: '请输入金额',
                        trigger: ['blur', 'change']
                      },
                      {
                        pattern: REGEX_PRICE_NUMBER,
                        message: '请输入整数，可保留两位小数',
                        trigger: ['blur', 'change']
                      }
                    ]"
                    label-width="0"
                  >
                    <el-input
                      v-model="item.incrementCashPrice"
                      style="height: 30px; padding: 0 10px"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-button class="mt-20" type="primary" @click="addRegion"
            >添加<i class="el-icon-plus"></i
          ></el-button>
        </div>

        <el-form-item class="mt-20" label="是否默认：" required>
          <el-radio-group v-model="formData.isDefault">
            <el-radio v-for="(item, index) in DEFAULTSTATUS" :key="index" :label="item.value">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否启用：" required>
          <el-radio-group v-model="formData.isShow">
            <el-radio v-for="(item, index) in STATUS" :key="index" :label="item.value">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item class="text-center">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 投放区域 -->
    <RegionTree
      ref="aresTree"
      v-if="dialogVisible"
      :dialog-visible.sync="dialogVisible"
      @getAreaSelect="getAreaSelect"
    />
  </div>
</template>

<script>
import _ from 'lodash'
import rules from './rules'
import { useGenerateUUID } from '@/hooks'
import { IS_STATUS } from '@/enum'
// import { deepClone, treeToList } from '@/utils'
import { REGEX_PRICE_NUMBER, REGEX_POSITIVE_INTEGER } from '@/utils/validate'
export default {
  name: 'AddTemplate',
  mixins: [rules],
  data() {
    return {
      dialogVisible: false,
      formData: {
        isShow: true,
        isDefault: true,
        chargeMode: 1,
        name: '',
        defaultCharge: {
          firstCashPrice: '', //首选价格（现金）
          firstValue: '', // 首选值（件/重量）
          incrementCashPrice: '', // 增量价格（现金）
          incrementValue: '' // 增量值（件/重量）
        },
        listCharge: []
      },
      BILLING_METHODS: [
        {
          label: '按件数',
          value: 1
        },
        {
          label: '按重量',
          value: 2
        },
        {
          label: '卖家包邮',
          value: 3
        }
      ],
      DEFAULTSTATUS: [
        {
          label: '默认',
          value: true
        },
        {
          label: '非默认',
          value: false
        }
      ],
      uuid: ''
    }
  },
  computed: {
    id() {
      return this.$route.query?.id
    },
    STATUS() {
      return IS_STATUS
    },
    // 校验价格
    REGEX_PRICE_NUMBER() {
      return REGEX_PRICE_NUMBER
    },
    // 校验数量
    REGEX_POSITIVE_INTEGER() {
      return REGEX_POSITIVE_INTEGER
    }
  },
  created() {
    this.getExpressTemplateDetail()
  },
  mounted() {
    this.$nextTick(() => {
      let fareItemHeight = document.getElementById('fare-item').offsetHeight
      document.getElementById('fare-box').style.height = fareItemHeight + 'px'
    })
  },
  methods: {
    //选择开放区域
    addRegion() {
      this.uuid = ''
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.aresTree.initData([])
      })
    },
    // 修改开放区域
    editRegion({ uuid, id, areaList }) {
      this.dialogVisible = true
      this.uuid = id || uuid
      this.$nextTick(() => {
        this.$refs.aresTree.initData(areaList)
      })
    },
    // 删除开放区域
    deleteRegion(index) {
      this.formData.listCharge = this.formData.listCharge.filter((item, cIndex) => index !== cIndex)
    },
    getAreaSelect({ selctArea, selctIdArea }) {
      // 选中的ids
      let areaIds = selctIdArea
        .filter(item => item.levelType === 2)
        .map(v => v.id)
        ?.join(',')

      // 修改
      if (this.uuid) {
        this.formData.listCharge = this.formData.listCharge.map(item => {
          let id = item.id || item.uuid
          if (id === this.uuid) {
            item.areaIds = areaIds
            item.areaList = selctArea
          }
          return item
        })
      } else {
        // 新增
        this.formData.listCharge = [
          ...this.formData.listCharge,
          {
            uuid: useGenerateUUID(),
            areaIds,
            areaList: selctArea,
            firstCashPrice: '',
            firstValue: '',
            incrementCashPrice: '',
            incrementValue: ''
          }
        ]
      }
    },
    // 获取参数
    getParams() {
      const params = this.$lodash.cloneDeep(this.formData)
      if (this.formData.chargeMode === 3) {
        delete params.defaultCharge
        delete params.listCharge
      }
      if (params.listCharge?.length) {
        delete params.defaultCharge.updatedTime
        delete params.defaultCharge.createdTime

        params.listCharge = params.listCharge.map(item => {
          return {
            id: item.id,
            areaIds: item.areaIds,
            firstValue: item.firstValue,
            firstCashPrice: item.firstCashPrice,
            incrementValue: item.incrementValue,
            incrementCashPrice: item.incrementCashPrice
          }
        })
      }
      return params
    },
    // 新增快递模版
    addExpressTemplate: _.debounce(async function () {
      const params = this.getParams()
      const { status, msg } = await this.$http.express.templateApi.addExpressTemplate(params)
      if (status === 200) {
        this.$message.success('新增成功！')
        this.$router.back(-1)
      } else {
        this.$message.error(msg)
      }
    }, 200),
    // 获取快递模版详情
    async getExpressTemplateDetail() {
      if (!this.id) return
      const { data } = await this.$http.express.templateApi.getExpressTemplateDetail(this.id)

      let formDataKeys = Object.keys(this.formData)

      for (const key in data) {
        if (formDataKeys.includes(key)) {
          this.formData[key] = data[key]
        }
      }
      console.log(this.formData, 'formData')
    },
    // 编辑快递模版
    updateExpressTemplate: _.debounce(async function () {
      const params = this.getParams()
      const { status, msg } = await this.$http.express.templateApi.updateExpressTemplate({
        id: this.id,
        ...params
      })
      if (status === 200) {
        this.$message.success('编辑成功！')
        this.$router.back(-1)
      } else {
        this.$message.error(msg)
      }
    }, 200),
    // 提交
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        console.log(this.formData)
        if (!valid) return
        if (this.id) {
          this.updateExpressTemplate()
        } else {
          this.addExpressTemplate()
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$router.back(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-elform {
  /deep/ .el-form-item__content {
    margin-left: 0 !important;
  }
}
</style>
